<?php
namespace Apps\Acp\Controllers;

use Apps\Common\Constant\BusinessConstant;
use Apps\Common\Controller\AcpBaseController;
use Apps\Weixin\Models\WxAuthInfo;
use Apps\Weixin\Services\WxHelperService;
use Deyi\Functions\PageFunction;

class AppsController extends AcpBaseController
{
    public function indexAction()
    {
        $appId = $this->getParamValue('appid', '');

        $page = PageFunction::getPageAndOffset($this->getParamValue('page', 1, 'int'), BusinessConstant::PAGE_SIZE);

        $conditions = [];

        if ($appId) {
            $conditions['appid'] = $appId;
        }

        $total = WxAuthInfo::getInstance()->countListByConditions($conditions);
        $list = [];
        if ($total) {
            $list = WxAuthInfo::getInstance()->getListByConditions($conditions, $page['offset'], $page['size']);
            $authInfos = [];
            foreach ($list as $v) {
                if (!$v->auth_info) {
                    continue;
                }
                $authInfos[$v->appid] = json_decode($v->auth_info);
            }
        }

        $this->view->setVars([
            'list' => $list,
            'pageHtml' => PageFunction::getPageHtml(
                $page['page'],
                $total,
                $page['size'],
                parse_url($this->request->getURI())['path'],
                [
                    'code' => $appId
                ],
                4
            ),
            'appid' => $appId,
            'authinfo' => $authInfos,
            'funcinfo' => BusinessConstant::WX_FUNC_INFO_GROUP
        ]);

    }

    public function syncInfoAction()
    {
        $appId = $this->getParamValue('appid');

        if ($res = WxHelperService::getInstance()->getAuthorizerInfo($appId)) {
            WxAuthInfo::getInstance()->updateByFields(['auth_info' => json_encode($res, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)], ['appid' => $appId]);
            parent::renderSuccessJson();
        } else {
            static::errorThrow('同步数据失败');
        }
    }
}